import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {connect} from 'react-redux';
import {sendNotify} from '../actions/asist';
import render from '../renderers/index';
import * as DocumentTitle from 'react-document-title';

let index = 1;
export default function make(item, title, data) {
  const pageId = index++;

  if (!item.schema && !item.component) {
    item = {schema: item};
  }

  class RouteWrapper extends PureComponent {

    static contextTypes = {
      can: PropTypes.func
    };


    render() {
      const {
        sendNotify,
        location,
        params,
        data: propsData
      } = this.props;

      if (item.acl && this.context.can && !this.context.can(item.acl)) {
        return (
          <div className="container w-xxl w-auto-xs">
            <div className="text-center m-b-lg">
              <h1 className="text-shadow text-white">403</h1>
            </div>
            <div className="text-center">
              <p className="text-muted">权限不够</p>
            </div>
          </div>
        );
      }

      const RouteComponent = item.component;
      const body = RouteComponent ? <RouteComponent {...this.props} /> : render('page', item.schema, {
        location,
        sendNotify,
        $scopedPrefix: pageId,
        key: location.pathname,
        data: {
          ...location.query,
          ...params,
          ...propsData,
          ...data,
          params
        },
        pageId
      });

      return title ? (
        <DocumentTitle title={`${title} -- ${window.vars && window.vars.orgName || '志多星'}`}>
          {body}
        </DocumentTitle>
      ) : body;
    }
  }

  if (item.schema) {
    return connect(null, {
      sendNotify
    })(RouteWrapper);
  }

  return RouteWrapper;
}
